package com.ogj.newstar.util;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class HttpUtils {
	private static Integer urlCount=0;
	private final static Integer max_Number=2;

	/**
	 * 发送GET请求，并返回响应内容的方法
	 * @param urlStr 请求的url
	 * @return 响应数据
	 */
	public static String get(String urlStr){
        String message="";
        //定义Lock锁
        try {
            URL url=new URL(urlStr);
            HttpURLConnection connection= (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setConnectTimeout(20*1000);
            connection.connect();
            InputStream inputStream=connection.getInputStream();
            byte[] data=new byte[1024*512];// 512kb缓存空间
            StringBuffer sb=new StringBuffer();
            int length=0;
            while ((length=inputStream.read(data))!=-1){
                String s=new String(data,0,length);
                sb.append(s);
            }
            message=sb.toString();
//            int a=1/0;
        } catch (Exception e) {
            e.printStackTrace();
            try {
				Thread.sleep(2*1000);
			} catch (InterruptedException e1) {
				e1.printStackTrace();
			}
            urlCount++;
            System.out.println("访问失败次数:"+urlCount);
            if(urlCount>=max_Number){
                urlCount=0;
                return message;
            }
            return get(urlStr);
        }
        System.out.println(Thread.currentThread().getName()+"-----访问成功------");
        return message;
    }

}

